/***************************************************************************
 *
 *   copyright            : (C) 2005 Winds of Storm
 *
 *   $Id: primordial.c,v 1.18 2007/02/10 12:40:34 nathan Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#include "sb.h"

#ifdef __sun__
extern size_t      strnlen(char const *, size_t);

char * strndup (const char *s, size_t n) {
	size_t len = strnlen (s, n);
	char *new = malloc (len + 1);

	if (new == NULL)
		return NULL;

	new[len] = '\0';
	return memcpy (new, s, len);
}
#endif

void primordial_soup(DESCRIPTOR_DATA *desc, IO_BUFFER *input_buff) {
	char		buffer[MAX_STRING_LENGTH];
	DB_RES		*results;
	DB_ROW		row;

	sb_log(LOG_INFO, "desc #%d: attempting to rise out of the primordial soup, status %d", desc->descriptor, desc->conn_status);
	if (!strncasecmp(input_buff->buffer, "GET /?sid=", 10)) {
		desc->session_id	= strndup(input_buff->buffer + 10, 32);

		add_to_output_queue(desc, "<br /><b>SID: ");
		add_to_output_queue(desc, (char *)desc->session_id);
		add_to_output_queue(desc, "</b><br />");

		// Got the session ID string, send greeting
		send_greeting_to_desc(desc);

        	sprintf(buffer, "SELECT user_id,room_id,username,server_push FROM %ssessions WHERE session_id='%s'", 
				db_pfx, (char *)desc->session_id);

		pthread_mutex_lock(&db_mutex);
        	results = db_query(dbconn, buffer);
		pthread_mutex_unlock(&db_mutex);

        	if (results != NULL) {
                	row             = db_fetch_row(results, 0);
                	if (row != NULL) {
                        	if (atoi(row[0]) != desc->user_id) {
                                	desc->user_id   = atoi(row[0]);
					sb_log(LOG_INFO, ">>>>>>>DESC %d<<<<<<< set user id to %d", desc->descriptor, desc->user_id);
                        	}
                        	if (atoi(row[1]) != desc->room_id) {
                                	desc->room_id   = atoi(row[1]);
					sb_log(LOG_INFO, ">>>>>>>DESC %d<<<<<<< set room id to %d", desc->descriptor, desc->room_id);
                        	}
				desc->username	= strdup(row[2]);
				sb_log(LOG_INFO, ">>>>>>>DESC %d<<<<<<< set username to %s", desc->descriptor, desc->username);

				if (atoi(row[3]) == MODE_SERVER_PUSH) {
					add_to_output_queue(desc, "\t<script type=\"text/javascript\">\r\n");
					add_to_output_queue(desc, "\t\tdocument.domain='");
					add_to_output_queue(desc, site_domain);
					add_to_output_queue(desc, "'\r\n");
					add_to_output_queue(desc, "\t</script>\r\n");
				}
				desc->conn_status	= CON_CHATTING;
                	} else {
				sb_log(LOG_INFO, "descriptor %d does not have a valid session ID...", desc->descriptor);
                        	add_to_output_queue(desc, "Session not valid, please log back in.");
                        	// session no longer valid, nix it
				desc->conn_status	= CON_QUITTING;
                	}
                	db_clean_results(results);


                        //
                        // Send custom CSS headers
                        //
                        sprintf(buffer, "SELECT user_css FROM %ssessions AS s,%sprefs AS p WHERE p.user_css != '' AND p.user_id=s.user_id AND s.session_id='%s'",
                                        db_pfx, db_pfx, (char *)desc->session_id);

                        pthread_mutex_lock(&db_mutex);
                        results = db_query(dbconn, buffer);
                        pthread_mutex_unlock(&db_mutex);

                        //sb_log(LOG_INFO, "Selecting user_css...");
                        if (results != NULL) {
                                //sb_log(LOG_INFO, "Fetching user_css row from results...");
                                row     = db_fetch_row(results, 0);
                                if (row != NULL) {
                                        sb_log(LOG_INFO, "Sending user_css to %s...", (char *)desc->username);
                                        add_to_output_queue(desc, "<script>addCSS('<style type=text/css>");
                                        add_to_output_queue(desc, row[0]);
                                        add_to_output_queue(desc, "</style>');</script>\r\n");
                                }
                                db_clean_results(results);
                        }
        	}

	}
}

void send_greeting_to_desc(DESCRIPTOR_DATA *desc) {
	DB_RES	*results;
	DB_ROW	row;
	char	buffer[MAX_STRING_LENGTH];
	int	sent_greeting	= 0;

	sprintf(buffer, "SELECT * FROM %smotds WHERE motd_type=111 ORDER BY RAND() LIMIT 1", db_pfx);
	pthread_mutex_lock(&db_mutex);
	results = db_query(dbconn, buffer);
	pthread_mutex_unlock(&db_mutex);
	if (results != NULL) {
		row = db_fetch_row(results, 0);
		if (row != NULL) {
			sb_log(LOG_INFO, "Retrieved greeting #%d successfully", atoi(row[0]));
			add_to_output_queue(desc, "<script>SendToChat('<pre>");
			add_to_output_queue(desc, row[1]);
			add_to_output_queue(desc, "</pre>');</script>\r\n");
			db_clean_results(results);
			sent_greeting++;
		}
	}
	if (!sent_greeting) {
		add_to_output_queue(desc, "Welcome to StormChat!\r\n");
		add_to_output_queue(desc, "\r\n");
	}
}
